import { Component } from 'react'
import Taro from '@tarojs/taro'
import {View, Text, Textarea} from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      form: {
        title: '',
        rent: '',
        regionId: '',
        model: '',
        villageName: '',
        area: '',
        address: '',
        level: '',
        direction: '',
        pics: '',
        phone: '',
        username: ''
      },
      loading: false,
      editable: true,
      isApply: false
    }
    this.submitForm = this.submitForm.bind(this)
  }

  componentWillMount () {
  }

  componentDidMount () {
  }

  componentWillUnmount () {
  }

  componentDidShow () { }

  componentDidHide () { }

  validateForm(form) {

    if (!form.title) {
      Taro.showToast({
        title: '请输入标题！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.phone) {
      Taro.showToast({
        title: '请输入联系方式！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.village) {
      Taro.showToast({
        title: '请输入小区！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.rent) {
      Taro.showToast({
        title: '请输入租金！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.model) {
      Taro.showToast({
        title: '请输入户型',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.area) {
      Taro.showToast({
        title: '请输入面积！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.address) {
      Taro.showToast({
        title: '请输入地址！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.userName) {
      Taro.showToast({
        title: '请输入姓名！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.pics) {
      Taro.showToast({
        title: '请上传图片！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    return true;
  }

  async submitForm() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let { form } = this.state;
    if (!this.validateForm(form)) {
      this.setState({
        loading: false
      });
      return;
    }
    form.userId = global.userInfo.userId;
    form.status = '1';
    try {
      let res = await Request.post('/business/rental_house', form);
      if (res.data.code !== 200) {
        throw new Error();
      }
      await Taro.navigateBack();
      await Taro.showToast({
        title: '提交成功！',
        icon: "success",
        duration: 1000
      });
      Event.emit('updateHouses');
    } catch (e) {
      await Taro.showToast({
        title: '提交失败请重试',
        icon: "error",
        duration: 1000
      })
    } finally {
      this.setState({
        loading: false
      });
    }

  }

  async uploadImg() {
    try {
      let res = await Taro.chooseImage();
      await Taro.showLoading({
        title: '上传中'
      });
      let uploadFileRes = await Taro.uploadFile({
        url: Request.host + '/common/upload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Authorization': global.token
        },
        success: async (res) => {
          let data = JSON.parse(res.data)
          if (data.code !== 200) {
            throw new Error();
          }
          if (!this.state.form.pics) {
            this.state.form.pics = data.fileName;
          } else {
            this.state.form.pics += `,${data.fileName}`;
          }
          this.setState({
            form: this.state.form
          })
          await Taro.hideLoading();
          await Taro.showToast({
            title: '上传成功！',
            type: 'success'
          })
        }
      });
    } catch (e) {
      console.log("上传文件失败")
    } finally {
      await Taro.hideLoading();
    }
  }


  render () {
    let { form, loading, editable, isApply} = this.state;

    let pics = form.pics.split(',');

    let msgComponent = <Text className='msg_container color-blue'>{global.isApplyJob ? '请点击投递进行职位申请' : '填入以下信息进行房源发布'}</Text>;


    return (
      <View className='binding_container'>
        <View className='auth_msg_container'>
          {isApply ? <Text className='msg_container color-blue'>投递完成，请您耐心等待回复</Text> : msgComponent}
        </View>
        <View className='input_item'>
          <Text className='required'>标题</Text>
          <Input disabled={!editable} value={form.title} onInput={(e) => {this.setState({form: {...form, title: e.detail.value}})}} type='text' placeholder='请输入标题'/>
        </View>
        <View className='input_item'>
          <Text className='required'>小区</Text>
          <Input disabled={!editable} value={form.village} onInput={(e) => {this.setState({form: {...form, village: e.detail.value}})}} type='text' placeholder='小区名称'/>
        </View>
        <View className='input_item'>
          <Text className='required'>租金</Text>
          <Input disabled={!editable} value={form.rent} onInput={(e) => {this.setState({form: {...form, rent: e.detail.value}})}} type='text' placeholder='1200元/月、面议'/>
        </View>
        <View className='input_item'>
          <Text className='required'>户型</Text>
          <Input disabled={!editable} value={form.model} onInput={(e) => {this.setState({form: {...form, model: e.detail.value}})}} type='text' placeholder='三室两厅、面议'/>
        </View>
        <View className='input_item'>
          <Text className='required'>面积</Text>
          <Input disabled={!editable} value={form.area} onInput={(e) => {this.setState({form: {...form, area: e.detail.value}})}} type='text' placeholder='100平方'/>
        </View>
        <View className='input_item'>
          <Text>楼层</Text>
          <Input disabled={!editable} value={form.level} onInput={(e) => {this.setState({form: {...form, level: e.detail.value}})}} type='text' placeholder='6楼、中层'/>
        </View>
        <View className='input_item'>
          <Text>朝向</Text>
          <Input disabled={!editable} value={form.direction} onInput={(e) => {this.setState({form: {...form, direction: e.detail.value}})}} type='text' placeholder='朝南、朝北'/>
        </View>
        <View className='input_item'>
          <Text className='required'>地址</Text>
          <Textarea disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='房屋地址'/>
        </View>
        <View className='input_item'>
          <Text>描述</Text>
          <Textarea disabled={!editable} value={form.des} onInput={(e) => {this.setState({form: {...form, des: e.detail.value}})}} type='text' placeholder='房屋年代、地理优势、基础设施...'/>
        </View>
        <View className='input_item'>
          <Text className='required'>姓名</Text>
          <Input disabled={!editable} value={form.userName} onInput={(e) => {this.setState({form: {...form, userName: e.detail.value}})}} type='text' placeholder='请输入联系姓名'/>
        </View>
        <View className='input_item'>
          <Text className='required'>电话</Text>
          <Input disabled={!editable} value={form.phone} onInput={(e) => {this.setState({form: {...form, phone: e.detail.value}})}} type='text' placeholder='请输入联系电话'/>
        </View>
        <View className='input_item'>
          <Text className='required'>图片</Text>
          {/*<Input disabled={!editable} value={form.address} onInput={(e) => {this.setState({form: {...form, address: e.detail.value}})}} type='text' placeholder='请输入公司地址'/>*/}
          <View className='img-upload'>
            <View className='img_upload_container'>
              {
                form.pics && pics.map(item => <Image className='image_container' src={Request.imgHost + item}/>)
              }
              {
                editable && pics.length < 8 && <View className='image_container' onClick={this.uploadImg.bind(this)}>
                  <Text className='iconfont icon-add size50 cars_list'/>
                </View>
              }
            </View>
            {
              editable && <Text className='size28 tips'>最多支持上传8张图片</Text>
            }
          </View>
        </View>
        {
          editable && <Button loading={loading} className='submit_btn' type='primary' onClick={this.submitForm}>发布房源</Button>
        }
        {
          editable && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 请确保该信息真实有效，我们将随时进行核实</Text>
          </View>
        }
      </View>
    )
  }
}
